import {
	createRouter,
	createWebHistory,
	RouteRecordRaw,
	NavigationGuardNext,
	RouteLocationNormalized,
} from 'vue-router'
import { HomeItem } from './modules/home'

import { getToken } from '@/utils/auth'

const routes: Array<RouteRecordRaw> = [
	{
		path: '/login',
		component: () => import('@/views/home/login.vue'),
	},
	{
		path: '/',
		redirect: '/home',
	},
	{
		path: '/home',
		name: 'home',
		redirect: '/home/index',
		component: () => import('@/views/home/index.vue'),
		children: HomeItem,
	},
	// {
	// 	path: '/dataManage',
	// 	name: 'dataManage',
	// 	redirect: '/dataManage/index',
	// 	component: () => import('@/views/dataManage/index.vue'),
	// 	children: DataManageItem,
	// },
	{
		// 匹配所有路径  vue2使用*   vue3使用/:pathMatch(.*)*或/:pathMatch(.*)或/:catchAll(.*)
		path: '/:pathMatch(.*)',

		component: () => import('@/views/404/index.vue'),
	},
]

const router = createRouter({
	history: createWebHistory(),
	routes,
})
const isAuthenticated = () => {
	const token = getToken()
	if (token) {
		return true
	} else {
		return false
	}
}
// 添加导航守卫
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
	// next()
  if (!isAuthenticated() && to.path !== '/login') {
		// 如果用户未登录且尝试访问非登录页面，则跳转到登录页
		next('/login')
	} else if (isAuthenticated() && to.path === '/login') {
		// 如果用户已登录且尝试访问登录页面，则重定向到首页
		next('/')
	} else {
		// 否则，允许访问
		next()
	}
})
export default router
